﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace Smarly.Bussines.Extentions
{
	public static class StringExtentions
	{
		public static string HtmlStript(this string html, int length)
		{
			string result = string.Empty;

			int counter = 0;

			char[] breakChars = new[] { ' ', '\r', '\n' };

			for (int i = 0; i < html.Length; i++)
			{

				char currentCharacter = html[i];

				if (counter >= length && breakChars.Any(x => x == currentCharacter))
				{
					result += " ...";
					break;
				}

				if (currentCharacter == '<')
				{
					i = html.IndexOf('>', i);
				}
				else
				{
					result += currentCharacter;
					counter++;
				}
			}

			return result;
		}

		public static string HTMLSubstring(this string html, int length, bool withDotes = true)
		{
			List<string> unclosedTags = new List<string>();

			string result = string.Empty;

			int counter = 0;

			bool isQuoted = false;

			char[] breakChars = new char[] { ' ' };

			if (html.Length > length)
			{
				for (int i = 0; i < html.Length; i++)
				{

					char currentCharacter = html[i];

					if (counter >= length && breakChars.Any(x => x == currentCharacter))
					{
						if (withDotes)
							result += " ...";
						break;
					}

					if (currentCharacter == '<')
					{
						var tagIndex = html.IndexOf('>', i) + 1;
						var tag = html.Substring(i, tagIndex - i);
						var tagName = tag.Trim('>', '<', '/').Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries)[0];
						if (tag.Trim('>', '<').Trim().StartsWith("/"))
						{
							var index = unclosedTags.Count - 1;
							if (index >= 0)
							{
								var lastTag = unclosedTags[index];
								if (lastTag != tagName)
								{
									result += tag;
								}
							}

							result += "</" + tagName + ">";
							if (index >= 0)
								unclosedTags.RemoveAt(index);

							i = tagIndex - 1;

						}
						else
						{
							unclosedTags.Add(tagName);
							result += tag;
							i = tagIndex - 1;
						}
					}
					else
					{
						result += currentCharacter;
						counter++;
					}
				}
			}
			else
			{
				result = html;
			}
			unclosedTags.Reverse();
			foreach (var tagName in unclosedTags)
			{
				result += "</" + tagName + ">";
			}

			return Regex.Replace(result, @"(</br>|</ br>|<br>|\s)*$", ""); 
		}
	}
}